package com.my.blogapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.my.blogapi.dao.dos.Archives;
import com.my.blogapi.dao.mapper.ArticleBodyMapper;
import com.my.blogapi.dao.mapper.ArticleMapper;
import com.my.blogapi.dao.mapper.ArticleTagMapper;
import com.my.blogapi.dao.mapper.CategoryMapper;
import com.my.blogapi.dao.pojo.*;
import com.my.blogapi.service.*;
import com.my.blogapi.utils.UserThreadLoacl;
import com.my.blogapi.vo.ArticleBodyVo;
import com.my.blogapi.vo.ArticleVo;
import com.my.blogapi.vo.CategoryVo;
import com.my.blogapi.vo.TagVo;
import com.my.blogapi.vo.param.ArticleParam;
import com.my.blogapi.vo.param.PageParams;
import com.my.blogapi.vo.param.Result;
import org.apache.ibatis.jdbc.Null;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional
public class ArticleServiceImpl implements ArticleService {

    @Resource
    private ArticleMapper articleMapper;
    @Autowired
    private TagService tagService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ArticleBodyMapper articleBodyMapper;

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ThreadService threadService;
    @Autowired
    private ArticleTagMapper articleTagMapper;

    /**
     * 文章分页查询
     *
     * @param pageParams
     * @return
     * @date 2021年9月20日19:16:34
     */
    @Override
    public Result listArticle(PageParams pageParams) {
        if (pageParams.getYear() != null && pageParams.getMonth() != null) {
            return listArticleByMonthAndYear(pageParams);
        }
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate, Article::getWeight);
        if (pageParams.getCategoryId() != null) {
            queryWrapper.eq(Article::getCategoryId, pageParams.getCategoryId());
        }
        Integer tagId = pageParams.getTagId();
        if (tagId != null) {
            //通过标签ID去查询对应的文章ID
            LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
            articleTagLambdaQueryWrapper.eq(ArticleTag::getTagId, tagId);
            List<ArticleTag> articleTagList = articleTagMapper.selectList(articleTagLambdaQueryWrapper);
            if (articleTagList.size() > 0) {
                queryWrapper.in(Article::getId, articleTagList);
            }

        }
        //按照创建时间排序
        queryWrapper.orderByDesc(Article::getCreateDate, Article::getCreateDate);

        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
        List<Article> records = articlePage.getRecords();
        //我们期望的是直接返回前端页面需要的数据，而数据库中查询出来的数据又不能满足要求，所以我们要加工一下
        //我们articleVO来分装我们前端需要的数据
        List<ArticleVo> articleVoList = copyList(records, true, true);
        return Result.success(articleVoList);
    }

    private Result listArticleByMonthAndYear(PageParams pageParams) {
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        IPage<Article> listPage = articleMapper.listArticle(page, pageParams.getCategoryId(),
                pageParams.getTagId(),
                pageParams.getYear(),
                pageParams.getMonth());
        List<Article> articleList = listPage.getRecords();
        return Result.success(copyList(articleList,true,true));
    }

    /**
     * 最新文章
     *
     * @param limit
     * @return
     */
    @Override
    public Result newArticle(int limit) {
        //按时间排序取前五条
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate);
        queryWrapper.last("limit " + limit);
        List<Article> articleList = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articleList, false, false));
    }

    /**
     * 文章归档
     *
     * @return
     */
    @Override
    public Result listArchives() {
        List<Archives> archivesList = articleMapper.listArchives();
        return Result.success(archivesList);
    }

    /**
     * 根据ID查询文章
     *
     * @param articleId
     * @return
     */
    @Override
    public Result findArticleById(Long articleId) {
        Article article = articleMapper.selectById(articleId);
        //多线程 更新阅读数量
        threadService.updateArticleViewCount(articleMapper, article);
        return Result.success(copy(article, true, true, true, true));
    }

    /**
     * 发布文章
     *
     * @param articleParam
     * @return
     */
    @Override
    public Result publishArticle(ArticleParam articleParam) {
        /**
         * 1.发布文章 构建Article
         * 2.作者id 当前登录用户的id
         * 3.标签 要将标签加入到关联列表中
         * 4.body内容存储article_bodyId
         */
        Article article = new Article();
        article.setSummary(articleParam.getSummary());
        article.setTitle(articleParam.getTitle());
        article.setCommentCounts(0);
        article.setViewCounts(0);
        article.setWeight(Article.Article_Common);
        article.setCreateDate(System.currentTimeMillis());
        //类别
        article.setCategoryId(articleParam.getCategory().getId());
        this.articleMapper.insert(article);
        SysUser sysUser = UserThreadLoacl.get();
        if (sysUser != null) {
            article.setAuthorId(sysUser.getId());
        }
        //需要文章主体ID，只有先将文章主体插入才有文章主体ID
        ArticleBody articleBody = new ArticleBody();
        articleBody.setArticleId(article.getId());
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBodyMapper.insert(articleBody);
        //把ID赋值给Article对应articler_bodyId
        article.setBodyId(articleBody.getId());
        //做修改
        articleMapper.updateById(article);
        //对应的文章标签表也得做修改
        List<TagVo> tags = articleParam.getTags();

        if (tags != null) {
            for (TagVo tag : tags) {
                ArticleTag articleTag = new ArticleTag();
                articleTag.setArticleId(article.getId());
                articleTag.setTagId(tag.getId());
                articleTagMapper.insert(articleTag);
            }
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("id", article.getId().toString());
        return Result.success(map);
    }

    /**
     * 最热文章
     *
     * @param limit
     * @return
     */
    @Override
    public Result hotArticle(int limit) {
        /**
         * 根据浏览量选出浏览量最多的五条数据
         */
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getViewCounts);
        queryWrapper.select(Article::getId, Article::getTitle);
        queryWrapper.last("limit " + limit);
        List<Article> articleList = articleMapper.selectList(queryWrapper);
        //返回对应的Vo
        return Result.success(copyList(articleList, false, false));
    }

    private List<ArticleVo> copyList(List<Article> records, boolean isTags, boolean isAuthor) {
        ArrayList<ArticleVo> list = new ArrayList<>();
        for (Article record : records) {
            list.add(copy(record, isTags, isAuthor));
        }
        return list;
    }

    private ArticleVo copy(Article article, boolean isTags, boolean isAuthor) {
        //spring提供一个beanutils 可以将不同对象相同的属性值相互复制
        ArticleVo articleVo = new ArticleVo();
        //有一些属性需要我们手动来转
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        articleVo.setId(String.valueOf(article.getId()));
        BeanUtils.copyProperties(article, articleVo);
        //并不是所有的接口都需要标签，作者信息
        if (isTags) {
            //根据文章的ID去查询对应的标签
            Long articleId = article.getId();
            articleVo.setTags(tagService.findTagsByArticleId(articleId));
        }
        if (isAuthor) {
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(sysUserService.findSysUserByAuthorId(authorId).getNickname());
        }
        return articleVo;
    }

    private ArticleVo copy(Article article, boolean isTags, boolean isAuthor, boolean isArticleBody, boolean isCategory) {
        //spring提供一个beanutils 可以将不同对象相同的属性值相互复制
        ArticleVo articleVo = new ArticleVo();
        articleVo.setId(String.valueOf(article.getId()));
        //有一些属性需要我们手动来转
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        BeanUtils.copyProperties(article, articleVo);
        //并不是所有的接口都需要标签，作者信息
        if (isTags) {
            //根据文章的ID去查询对应的标签
            Long articleId = article.getId();
            articleVo.setTags(tagService.findTagsByArticleId(articleId));
        }
        if (isAuthor) {
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(sysUserService.findSysUserByAuthorId(authorId).getNickname());
        }
        if (isArticleBody) {
            ArticleBody articleBody = articleBodyMapper.selectById(article.getBodyId());
            ArticleBodyVo articleBodyVo = new ArticleBodyVo();
            BeanUtils.copyProperties(articleBody, articleBodyVo);
            articleVo.setBody(articleBodyVo);
        }
        if (isCategory) {
            Category category = categoryMapper.selectById(article.getCategoryId());
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(category, categoryVo);
            articleVo.setCategory(categoryVo);
        }
        return articleVo;
    }
}
